package com.example.demo.common.msg.service;


import com.example.demo.common.exception.EbsException;
import com.example.demo.common.file.service.FileService;
import com.example.demo.common.vo.EbsFile;
import com.example.demo.config.properties.EmailProperties;
import com.example.demo.core.constant.Constants;
import com.example.demo.core.util.AppConfig;
import com.example.demo.core.util.ExecTime;
import com.example.demo.core.util.SpringContextHolder;
import org.apache.commons.io.FilenameUtils;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.HtmlEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.HtmlUtils;

import javax.mail.internet.MimeUtility;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：闫广坤
 * 创建时间：2014-12-15
 * 功能描述：
 * 版本:2.0.0
 */
public class EmailService {

    private static final Logger logger = LoggerFactory.getLogger(EmailService.class);

    /**
     * 发送电子邮件.
     *
     * @param address 　邮件地址号多个用逗号分开.
     * @param title   　邮件标题.
     * @param content 邮件内容.
     * @throws Exception
     */
    public static boolean sendMail(String address, String title, String content) {

        return sendMail(address, title, content, "");
    }

    /**
     * 发送电子邮件.
     *
     * @param address 　邮件地址号多个用逗号分开.
     * @param title   　邮件标题.
     * @param content 邮件内容.
     * @param fileId  附件列表.
     */
    public static boolean sendMail(String address, String title, String content, String fileId) {
        return sendMail(address, title, content, fileId, "1");
    }

    /**
     * 发送电子邮件.
     *
     * @param address 　邮件地址号多个用逗号分开.
     * @param title   　邮件标题.
     * @param content 邮件内容.
     * @param fileId  附件列表.
     */
    public static boolean sendMail(String address, String title, String content, String fileId, String configType) {

        logger.info("发送Email,Email地址:" + address + ",内容:" + StringUtils.substring(content, 0, 100));

        try {
            List<EbsFile> fileList = new ArrayList<EbsFile>();

            if (StringUtils.isNotEmpty(fileId)) {
                FileService fileService = SpringContextHolder.getBean("ftpFileService");
                String[] fileIds = StringUtils.split(fileId, Constants.COMMA);
                for (String fId : fileIds) {
                    fileList.add(fileService.getFileById(fId));
                }
            }

            ExecTime execTime = new ExecTime();

            String[] addresss = address.split(",");

            for (int i = 0; i < addresss.length; i++) {
                _sendMail(addresss[i], title, content, fileList, configType);
            }

            logger.info("发送Email耗时:" + execTime.toString());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new EbsException(e);
            //return false;
        }
    }

    /**
     * 发送电子邮件.
     *
     * @param address  　邮件地址号多个用逗号分开.
     * @param title    　邮件标题.
     * @param content  邮件内容.
     * @param fileList 附件列表.
     */
    public static void sendMail(String address, String title, String content, List<EbsFile> fileList) {
        sendMail(address, title, content, fileList);
    }

    /**
     * 发送电子邮件.
     *
     * @param address  　邮件地址号多个用逗号分开.
     * @param title    　邮件标题.
     * @param content  邮件内容.
     * @param fileList 附件列表.
     */
    public static void sendMail(String address, String title, String content, List<EbsFile> fileList, String configType) {

        logger.info("发送Email,Email地址:" + address + ",内容:" + StringUtils.substring(content, 0, 100));
        ExecTime execTime = new ExecTime();

        String[] addresss = address.split(",");

        for (int i = 0; i < addresss.length; i++) {
            _sendMail(addresss[i], title, content, fileList, configType);
        }

        logger.info("发送Email耗时:" + execTime.toString());
    }

    private static void _sendMail(String address, String title, String content, List<EbsFile> fileList, String configType) {

        logger.debug("发送Email,toEmail:" + address + ",内容:" + StringUtils.substring(content, 0, 100));

        try {
            String hostName = SpringContextHolder.getBean(EmailProperties.class).getHostName();
            String smtpPort = SpringContextHolder.getBean(EmailProperties.class).getSmtpPort();
            String from = SpringContextHolder.getBean(EmailProperties.class).getFrom();
            String username = SpringContextHolder.getBean(EmailProperties.class).getUsername();
            String password = SpringContextHolder.getBean(EmailProperties.class).getPassword();


            int port = 25;

            if (StringUtils.isNotEmpty(smtpPort))
                port = new Integer(smtpPort);

            HtmlEmail email = new HtmlEmail();
            email.setCharset("UTF-8");
            email.setHostName(hostName);
            email.setSmtpPort(port);
            email.setAuthenticator(new DefaultAuthenticator(username, password));
            email.setFrom(from);

            email.addTo(address, getToName(address));
            email.setFrom(from, username);
            email.setSubject(title);
            email.setHtmlMsg(HtmlUtils.htmlUnescape(content));

            if (fileList != null && !fileList.isEmpty()) {
                int size = fileList.size();
                EbsFile ebsFile = null;
                for (int i = 0; i < size; i++) {
                    ebsFile = (EbsFile) fileList.get(i);
                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setPath(ebsFile.getFile().getAbsolutePath());
                    String name = MimeUtility.encodeText(FilenameUtils.getName(ebsFile.getFileName()));
                    attachment.setName(name);
                    email.attach(attachment);
                }
            }
            String result = email.send();
            logger.info("fromEmail:" + from + " 发送邮件结果:" + result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new EbsException(e);
        }
    }

    public static String getToName(String address) throws Exception {

        String ret = address;
        int i = StringUtils.indexOf(address, "@");
        if (i > 0)
            ret = StringUtils.substring(address, 0, i);

        return ret;
    }
}

